package org.wzq.test;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import org.wzq.config.AppConfig;
import org.wzq.config.AppUrl;
import org.wzq.mdm.R;
import org.wzq.utils.SpTool;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * project:
 * author: wzq
 * date: 2014/8/9
 * description:
 */
public class ActIpSetting extends Activity {
    private Context mCtx;
    private Button btnDone;
    private EditText etHostIp;
    private ListView lvIpList;
    private ArrayList<String> ipList = new ArrayList<String>();
    private ArrayAdapter adapter;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_ip_setting);

        mCtx = this;
        btnDone = (Button) findViewById(R.id.btn_done);
        etHostIp = (EditText) findViewById(R.id.et_host_ip);
        lvIpList = (ListView) findViewById(R.id.lv_ip_list);

        init();
    }

    private void init() {
        // etHostIp
        etHostIp.setText(AppUrl.getSocketIp());

        // btnDone
        btnDone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String hostIp = etHostIp.getText().toString().trim();
                // save and refresh
                if (!ipList.contains(hostIp)) {
                    String ipSrc = SpTool.getSp().getString(AppConfig.KEY_IP_LIST, "");
                    ipSrc += hostIp + ",";
                    SpTool.getSp().write(AppConfig.KEY_IP_LIST, ipSrc);

                    //
                    ipList.add(hostIp);
                    adapter.notifyDataSetChanged();
                }

                // back
                AppUrl.setSocketIp(hostIp);
                finish();
                // finish();
            }
        });

        // ip list
        setListAdapter();
        lvIpList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView tv = (TextView) view.findViewById(android.R.id.text1);
                etHostIp.setText(tv.getText());
            }
        });
    }

    private void setListAdapter() {
        String ipData = SpTool.getSp().getString(AppConfig.KEY_IP_LIST, "");
        String[] allIp = ipData.split(",");
        List<String> tmpList = Arrays.asList(allIp);
        ipList.addAll(tmpList);

        adapter = new ArrayAdapter<String>(mCtx,
                android.R.layout.simple_list_item_1,
                android.R.id.text1,
                ipList);

        lvIpList.setAdapter(adapter);
    }
}
